/*
 * @lc app=leetcode.cn id=29 lang=javascript
 *
 * [29] 两数相除
 */

// @lc code=start
/**
 * @param {number} dividend
 * @param {number} divisor
 * @return {number}
 */
var divide = function (dividend, divisor) {
  if (dividend === 0) {
    return 0;
  }
  if (divisor === 1) {
    return dividend;
  }
  if (divisor === -1 && dividend === -2147483648) {
    return 2147483647;
  }
  if (divisor === -1) {
    return -dividend;
  }
  if (divisor === 2 && dividend === -2147483648) {
    return -1073741824;
  }
  if (divisor === 2) {
    return dividend > 0 ? dividend >> 1 : -(-dividend >> 1);
  }
  if (divisor === -2 && dividend === -2147483648) {
    return 1073741824;
  }
  if (divisor === -2) {
    return dividend > 0 ? -(dividend >> 1) : (-dividend >> 1);
  }
  let negative;
  negative = (dividend ^ divisor) < 0;
  let t = dividend > 0 ? -dividend : dividend;
  let d = divisor > 0 ? -divisor : divisor;
  let result = 0;
  while (t <= d) {
    for (let i = 0; i <= 31; i++) {
      if ((d << i) < t) {
        result += 1 << (i - 1);
        t -= d << (i - 1);
        break;
      }
      if ((d << i) < (-1 << 30) || (d << i) === t) {
        result = result - (-1 << i);
        t -= d << i;
        break;
      }
    }
  }
  return negative ? -result : result;//符号相异取反
};
// @lc code=end

